//
//  HomeViewCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/11/27.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HomeViewCtrl.h"
#import "HBHomeCtrl.h"
#import "HBActivityCtrl.h"
#import "HBListSysNoticeInfo.h"
#import "HBListSysNoticeParam.h"
#import "HBListSysNoticeParser.h"
#import "HBMyMsgDetailCtrl.h"

@interface HomeViewCtrl ()<ViewPagerDataSource, ViewPagerDelegate>
{
    int         k;//(用来监听是否是第一次登陆首页)
    int         m;
    NSInteger   topScrollCount;
    NSArray*    topLibArr;
    NSArray*    topAlertArr;
    NSUInteger  topIndex;
    UIView*     topAlertView;
    UILabel*    topAlertLabel;
    UIButton*   topAlertBtn;
    NSString*   topStatus;
    NSString*   alertString;
    NSTimer*    timer;
    BOOL        isLanchHomeView;
}
@end

@implementation HomeViewCtrl
#define GetFinalresult(a,b) (isIphone4or5?a:b)

- (void)viewDidLoad {
    topLibArr = @[@"产品收益",@"更多活动"];
    self.dataSource = self;
    self.delegate = self;
    topScrollCount = 0;
    topStatus = @"0";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [self setTopAlertViewStatusWithStatus:topStatus];
    [super viewDidLoad];
}


- (void)buildLayout{
    
}

- (void)requestTopMessage{
    HBListSysNoticeParam* param = [[HBListSysNoticeParam alloc] init];
    HBListSysNoticeParser* parser = [[HBListSysNoticeParser alloc] init];
    [NetCenter getDataFromURL:Method_listSysNotice params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            HBListSysNoticeInfo* info = (HBListSysNoticeInfo*)myResult.result;
            topAlertArr = info.dataAry;
            alertString = [NSString string];
            //判断数组第一个元素是否为空，不为空则显示顶部的滚动条
            if ([topAlertArr count] > 0) {
                if (![topAlertArr[0] isEqualToString:@""]) {
                    [self creatTopUIWithString:topAlertArr[0]];
                    
                    topStatus = @"1";
                    NSDictionary* dic = [NSDictionary dictionaryWithObject:topStatus forKey:@"myindex"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"setNewFream" object:dic];
                }else{
                    topStatus = @"0";
                }

                }
            }else{
            topStatus = @"0";
            DISSMISS_ERR(myResult.message);
        }
        
    } failure:^(NSError *error) {
        topStatus = @"0";
        DISSMISS_ERR(error.description);
    }];
}

- (void)creatTopUIWithString:(NSString*)string{
    if (!topAlertView) {
        topAlertView = [[UIView alloc] initWithFrame:CGRectMake(0, GetFinalresult(-25, -25), SCREEN_WIDTH, GetFinalresult(25, 25))];
        [topAlertView setBackgroundColor:[LCCommon getColor:@"595959"]];
        [topAlertView setAlpha:1];
        topAlertLabel = [[UILabel alloc] initWithFrame:CGRectMake(topAlertView.size.width -30, 0, [string length]*15, GetFinalresult(25, 25))];
        [topAlertLabel setBackgroundColor:[UIColor clearColor]];
        [topAlertLabel setFont:[UIFont systemFontOfSize:14]];
        [topAlertLabel setTextColor:[LCCommon getColor:@"ffffff"]];
        [topAlertLabel setText:string];
        LLog(@"topAlertLabel.text ---- %@",topAlertLabel.text);
        [topAlertView addSubview:topAlertLabel];
        [topAlertLabel setUserInteractionEnabled:YES];
        
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topAlertViewTapAction:)];
        [topAlertLabel addGestureRecognizer:tap];
        [topAlertLabel setUserInteractionEnabled:YES];
        
        //用来挡住隐藏的label
        UIView* dangView = [[UIView alloc] initWithFrame:CGRectMake(topAlertView.size.width-40, 0, 40, GetFinalresult(25, 25))];
        [dangView setBackgroundColor:[LCCommon getColor:@"595959"]];
        [topAlertView addSubview:dangView];
        
        topAlertBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [topAlertBtn setFrame:CGRectMake(SCREEN_WIDTH -25,GetFinalresult(7, 7), 12, 12)];
        [topAlertBtn setCenterY:dangView.centerY];
        [topAlertBtn setBackgroundImage:[UIImage imageNamed:@"home_close"] forState:UIControlStateNormal];
        [topAlertBtn addTarget:self action:@selector(deleteTopAlert:) forControlEvents:UIControlEventTouchUpInside];
        [topAlertView addSubview:topAlertBtn];
        
        UIButton* topBigAlertBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [topBigAlertBtn setFrame:CGRectMake(SCREEN_WIDTH -30, 0, 30, GetFinalresult(25, 25))];
        
        
        [topBigAlertBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [topBigAlertBtn addTarget:self action:@selector(deleteTopAlert:) forControlEvents:UIControlEventTouchUpInside];
        [topAlertView addSubview:topBigAlertBtn];
    }
    [UIView animateWithDuration:0.3 animations:^{
        [topAlertView setFrame:CGRectMake(0.0, 0.0, SCREEN_WIDTH, GetFinalresult(25, 25))];
        [self.view addSubview:topAlertView];
        
    }];
    [self setTopAlertLabelScorllLeftWithString:string];
    timer = [NSTimer timerWithTimeInterval:0.015 target:self selector:@selector(setTopAlertLabelScorllLeftWithString:) userInfo:alertString repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)setTopAlertLabelScorllLeftWithString:(NSString*)string{
    CGFloat speace;
    speace = -1.0;
    CGFloat x = topAlertLabel.frame.origin.x;
    x += speace;
    [topAlertLabel setFrame:CGRectMake(x, 0, topAlertLabel.size.width, GetFinalresult(25, 25))];
    if (topAlertLabel.frame.origin.x == -topAlertLabel.size.width-10) {
        topScrollCount += 1;
        if (topScrollCount == topAlertArr.count) {
            //重置计数，避免后面的数组溢出
            topScrollCount = 0;
        }
        [topAlertLabel setFrame:CGRectMake(SCREEN_WIDTH-20, 0, [topAlertArr[topScrollCount] length]*15, GetFinalresult(25, 25))];
        topAlertLabel.text = topAlertArr[topScrollCount];
        topAlertLabel.tag = topScrollCount+10;
    }
}

- (void)topAlertViewTapAction:(UITapGestureRecognizer*)tap{
    LLog(@"点击第%ld顶部的view",tap.view.tag);
    UILabel* topLabel = (UILabel*)(tap.view);
    LLog(@"顶部的topLabel的消息是 ----- %@",topLabel.text);
    HBMyMsgDetailCtrl* detailVC = [[HBMyMsgDetailCtrl alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)setTopAlertViewStatusWithStatus:(NSString*)status{
    NSDictionary* dic = [NSDictionary dictionaryWithObject:topStatus forKey:@"myindex"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setNewFream" object:dic];
}

- (void)deleteTopAlert:(UIButton*)button{
    UIButton* bigButton = button;
    if (bigButton.selected == YES) {
        [topAlertBtn setSelected:YES];
    }
    [UIView animateWithDuration:0.35 animations:^{
        CGRect myFrame=self.view.frame;
        LLog(@"%lf",myFrame.origin.y);
        myFrame.origin.y=GetFinalresult(39, 39);
        self.view.frame=myFrame;
    }];
    topStatus = @"3";//消失
    NSDictionary* dic = [NSDictionary dictionaryWithObject:topStatus forKey:@"myindex"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setNewFream" object:dic];
}

- (void)viewWillAppear:(BOOL)animated{
    //这里接收过来的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTopPoint:) name:Notification_showTopPoint object:nil];
    //如果导航栏是透明的话,滚动视图要想让内部视图不上下溢出，需要设置下面的属性为NO
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = NO;

    if (!isLanchHomeView) {
        isLanchHomeView = YES;
        k = 5;
    }else{
        k = 0;
    }
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(k * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self requestTopMessage];
        if ([topStatus isEqualToString:@"0"]) {
            [self setTopAlertViewStatusWithStatus:topStatus];
        }else if([topStatus isEqualToString:@"1"]){
            [self setTopAlertViewStatusWithStatus:topStatus];
        }
//    });
}

- (void)viewWillDisappear:(BOOL)animated{
    //[topAlertView removeFromSuperview];
//    if (timer.isValid) {
//       将timer 内存进行调整，否则会计数retain
//    }
    [timer invalidate];//
    timer = nil;
//    [self removeFromParentViewController];
}

-(void)showTopPoint:(NSNotification*) notification{
    int n = [[[notification object] valueForKey:@"myindex"] intValue];
    topIndex = n;
    //设置顶部标签颜色
    UILabel* label = (UILabel*)[self.view viewWithTag:n+10];
    if (m ) {
        if (m-10 != n) {
            UILabel* label1 = (UILabel*)[self.view viewWithTag:m];
            [label1 setTextColor:[LCCommon getColor:@"929292"]];
        }
    }
    if (n == label.tag - 10) {
        [label setTextColor:[UIColor whiteColor]];
        m = n+10;
    }
}

#pragma mark - ViewPagerDataSource
- (NSUInteger)numberOfTabsForViewPager:(ViewPagerController *)viewPager {
    return topLibArr.count;
}
- (UIView *)viewPager:(ViewPagerController *)viewPager viewForTabAtIndex:(NSUInteger)index {
    
    UILabel *label = [UILabel new];
    [label setFrame:CGRectMake(0, 20, SCREEN_WIDTH/topLibArr.count, 44)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:17.0];
    label.text = topLibArr[index];
    label.tag = index + 10;
    
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [LCCommon getColor:@"929292"];
    [label sizeToFit];
    if (index == 0) {
        label.textColor = [UIColor whiteColor];
        m = 0+10;
    }
    LLog(@"%@",topLibArr[index]);
    return label;
}
//在这里添加需要写入的viewController
- (UIViewController *)viewPager:(ViewPagerController *)viewPager contentViewControllerForTabAtIndex:(NSUInteger)index {
    UIViewController* VC = [[UIViewController alloc] init];
    HBHomeCtrl* homeVC= [[HBHomeCtrl alloc] init];
    HBActivityCtrl* actVC = [[HBActivityCtrl alloc] init];
    if (index == 0) {
        VC = homeVC;
        homeVC.nav = self.navigationController;
    }else if(index == 1){
        VC = actVC;
        actVC.setNewframe = topStatus;
        actVC.nav = self.navigationController;
    }
      return VC;
}

#pragma mark - ViewPagerDelegate
- (CGFloat)viewPager:(ViewPagerController *)viewPager valueForOption:(ViewPagerOption)option withDefault:(CGFloat)value {
    switch (option) {
        case ViewPagerOptionTabWidth:
            return [[UIScreen mainScreen] bounds].size.width/topLibArr.count;
            break;
        default:
            break;
    }
    
    return value;
}

- (UIColor *)viewPager:(ViewPagerController *)viewPager colorForComponent:(ViewPagerComponent)component withDefault:(UIColor *)color {
    
    switch (component) {
        case ViewPagerIndicator:
            return [[LCCommon getColor:@"fa9838"] colorWithAlphaComponent:0.64];
            break;
        default:
            break;
    }
    
    return color;
}
- (void)showTopAlertView:(BOOL)isShow{
    if (isShow == YES) {
        [self.view addSubview:topAlertView];
        [UIView animateWithDuration:0.35 animations:^{
            CGRect myFrame=self.view.frame;
            myFrame.origin.y=64.0;
            self.view.frame=myFrame;
        }];
    }else if(isShow == NO){
        [UIView animateWithDuration:0.35 animations:^{
            CGRect myFrame=self.view.frame;
            myFrame.origin.y=20.0;
            self.view.frame=myFrame;
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
